var _ = require('underscore-min');

cc.Class({
    extends: cc.Component,
    properties: {
        currentHoodleLabel: cc.Label,   //当前弹珠数量
        springSprite: cc.Sprite,        //弹簧纵杆
        poleSprite: cc.Sprite,          //操纵杆
        hoodleSprite: cc.Sprite,        //弹珠
        ballLinkSprite: cc.Sprite,      //导航
        rankingNode: cc.Sprite,         //显示排行榜
        subContentNode: cc.Node,        //数据域
        egg0: cc.Node,                  //彩蛋节点1
        egg1: cc.Node,                  //彩蛋节点2
        gameStatus: 0,                  //【0初始化状态，1开始选球状态，2选定状态，3发射状态，4着陆状态】
        timeDownThreshold: 2,           //倒计时
        targetIndex: [],                //目标
        currentHoodleNumber: 5,         //初始数量
        shareMaxGive: 6,                //分享
        shareGive: 2,                   //分享一次赠送
        offsetY: 0,                     //Y形变
        timeDown: 0,                    //倒计时
        text: 'Hello, World!',
    },
    onLoad: function () {
        this.shareText = ["弹药不足，请求支援！",
            "奈斯，球进了！",
            "0.5%的彩蛋竟然被我遇上了？",
            "太好玩了，根本停不下来。",
            "为了玩好这游戏，重新学下物理和几何！"];
        cc.director.getPhysicsManager().enabled = true; // 开启物理
        cc.director.getCollisionManager().enabled = true; // 开启碰撞
        var self = this;
        this.currentHoodleLabel.string = this.currentHoodleNumber;
        this.poleSprite.node.on(cc.Node.EventType.TOUCH_START, this.onStartTouch, this);
        this.poleSprite.node.on(cc.Node.EventType.TOUCH_MOVE, this.onMoveTouch, this);
        this.poleSprite.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onEndTouch, this);
        this.poleSprite.node.on(cc.Node.EventType.TOUCH_END, this.onEndTouch, this);
        this.poleVec2 = this.poleSprite.node.position;                //记录操纵杆起始位置
        this.hoodleVec2 = this.hoodleSprite.node.position;            //记录弹珠起始位置
        this.angleVec2 = this.hoodleSprite.node.convertToWorldSpaceAR(cc.Vec2.ZERO);    //世界坐标
        this.springH = this.springSprite.node.height;                                   //记录弹簧原始高度
        this.ballLinkSprite.node.active = false;                                        //不显示导航条
        this.hoodleSprite.node.active = false;
        this.gameStatus = 0;
    },
    start() {
        console.log("初始化子域！");
        if (CC_WECHATGAME) {
            this.subContentNode.active = true;
            this.tex = new cc.Texture2D();
            window.wx.showShareMenu({withShareTicket: true});//设置分享按钮，方便获取群id展示群排行榜
            window.sharedCanvas.width = 720;
            window.sharedCanvas.height = 1280;
            window.wx.postMessage({
                messageType: 1,
                MAIN_MENU_NUM: "x1"
            });
        }
    },
    onShareButton() {
        console.log("分享按钮！");
        if (CC_WECHATGAME) {
            var self = this;
            window.wx.onShareAppMessage(function (res) {
                console.log(res);
                return {
                    title: self.shareText[_.random(0, self.shareText.length - 1)],
                    success(res) {
                        console.log("转发成功！");
                        self.currentHoodleNumber = self.currentHoodleNumber + 2;
                        self.currentHoodleLabel.string = self.currentHoodleNumber;  //更新显示
                    }
                };
            });
        } else {
            console.log("模拟转发成功！");
            this.currentHoodleNumber = this.currentHoodleNumber + 2;
            this.currentHoodleLabel.string = this.currentHoodleNumber;  //更新显示
        }
    },
    onCloseSubContent() {    //关闭子域
        this.subContentNode.active = false;
    },
    onStartTouch(eventTouch) {
        this.ballLinkSprite.node.active = true;
        this.ballLinkSprite.node.skewX = 0;
    },
    onGameReady() {
        if (this.currentHoodleNumber <= 0) {
            console.log("弹珠不足，分享到朋友圈领取2颗弹珠！");
            //分享获取
            var self = this;
            if (CC_WECHATGAME) {
                wx.onShareAppMessage(function (res) {
                    return {
                        title: self.shareText[_.random(0, self.shareText.length - 1)],
                        success(res) {
                            console.log("转发成功！");
                            self.currentHoodleNumber = self.currentHoodleNumber + 2;
                            self.currentHoodleLabel.string = self.currentHoodleNumber;  //更新显示
                        }
                    };
                });
            }
            return;
        }

        if (this.gameStatus === 0) {
            this.gameStatus = 1;
            var r = _.random(1, 3);
            var s = _.random(199);
            var e = _.random(199);
            console.log("random:" + s);
            if (s < 1) r = 8;
            else if (s < 3) r = 7;
            else if (s < 6) r = 6;
            else if (s < 10) r = 5;
            else if (s < 16) r = 4;
            else if (s < 30) r = 3;
            else if (s < 80) r = 2;
            else r = 1;
            //彩蛋
            this.egg0.active = false;
            this.egg1.active = false;
            if (e < 2) {        //显示彩蛋
                _.sample([this.egg0, this.egg1], 1)[0].active = true;
            }
            this.targetIndex = _.sample([0, 1, 2, 3, 4, 5, 6, 7], r);
            _.each(cc.find('ActiveNode', this.node).children, function (element) {
                element.getComponent(cc.Animation).play();
            });
            _.each(cc.find('ScoreNode', this.node).children, function (element) {
                element.getComponent(cc.Animation).play();
            });
            this.timeDownThreshold = 1 + _.random(0, 160) / 100;
            this.roundAudioID = cc.audioEngine.play(cc.url.raw("resources/sound/round.mp3"), false, 0.5);
        }
    },
    onMoveTouch(eventTouch) {
        this.ballLinkSprite.node.active = true;
        var a = eventTouch.getCurrentTarget();
        var startPoint = eventTouch.getStartLocation();   //起始位置
        var currentPoint = eventTouch.getLocation();  //当前位置
        var offsetY = (startPoint.y - currentPoint.y);
        if (offsetY < 0) offsetY = 0;
        if (offsetY >= this.springH - 50) offsetY = this.springH - 50;
        this.angle = this.getAngle(currentPoint, this.angleVec2);
        if (this.angle > 15) this.angle = 15;
        if (currentPoint.x > this.angleVec2.x) this.angle = 0 - this.angle;
        console.log(this.angle);
        this.ballLinkSprite.node.skewX = this.angle;
        this.springSprite.node.height = this.springH - offsetY;   //调整弹簧高度
        this.poleSprite.node.y = this.poleVec2.y - offsetY;
        this.offsetY = offsetY;
    },
    onEndTouch(eventTouch) {
        cc.audioEngine.play(cc.url.raw("resources/sound/pop.mp3"), false, this.offsetY / this.springH);
        if (this.gameStatus === 2) {  //开始状态
            this.gameStatus = 3;  //发射状态
            var hoodleRigidBody = this.hoodleSprite.node.getComponent(cc.RigidBody);
            this.angle = (_.random(5, 15) / 10) * this.angle;       //添加个随机变量，模拟手抖动
            var toY = Math.cos(2 * Math.PI / 360 * this.angle) * this.offsetY * 5 * (_.random(88, 126) / 10);   //计算X方向速度
            var toX = Math.sin(2 * Math.PI / 360 * this.angle) * this.offsetY * 5 * (_.random(88, 126) / 10);   //计算Y方向速度
            console.log("A:" + this.angle + "->" + "OFFSETY:" + this.offsetY);
            console.log("Y:" + toY + "->" + "X:" + toX);
            if (this.angle > 0) {
                toX = 0 - toX;
            }
            hoodleRigidBody.linearVelocity = cc.v2(toX, toY);
        }
        this.ballLinkSprite.node.active = false;
        this.ballLinkSprite.node.skewX = 0;
        var self = this;
        var actionBy = cc.sequence(cc.moveTo(0.1, cc.p(this.poleVec2.x, this.poleVec2.y)), cc.callFunc(function () {
            self.springSprite.node.height = self.springH;   //回调
        }, this, {}));
        this.poleSprite.node.runAction(actionBy);
    },
    egg: function (score) {
        console.log("彩蛋:"+score);
        this.currentHoodleNumber = this.currentHoodleNumber + parseInt(score);
        this.currentHoodleLabel.string = this.currentHoodleNumber;  //彩蛋分
    },
    analysisResult: function () {
        console.log("结果分析！");
        let self = this;
        this.gameStatus = 0;
        this.hoodleSprite.node.active = false;
        this.currentHoodleNumber = this.currentHoodleNumber - 1;
        let p1 = this.hoodleSprite.node.convertToWorldSpaceAR(cc.Vec2.ZERO);    //球的世界坐标点
        _.each(cc.find('ScoreNode', this.node).children, function (element, index) {
            let p2 = element.convertToWorldSpaceAR(cc.Vec2.ZERO);    //世界坐标点
            if (Math.abs(p1.x - p2.x) < 20) {
                if (_.indexOf(self.targetIndex, index) !== -1) {   //击中
                    let score = element.getChildByName("ScoreLabel").getComponent(cc.Label).string;
                    self.currentHoodleNumber = self.currentHoodleNumber + parseInt(score);
                    cc.audioEngine.play(cc.url.raw("resources/sound/right.mp3"), false, 0.5);
                    console.log("击中目标:+" + score);
                }
                else {
                    cc.audioEngine.play(cc.url.raw("resources/sound/error.mp3"), false, 0.5);
                }
                console.log(JSON.stringify([p1, p2]));
            }
        });
        this.currentHoodleLabel.string = this.currentHoodleNumber;  //减少
        this.resetAnimation();
        if (CC_WECHATGAME) {
            window.wx.postMessage({ //提交分数
                messageType: 3,
                MAIN_MENU_NUM: "x1",
                score: self.currentHoodleNumber
            });
        }
    },
    resetAnimation: function () { //重置动画状态
        _.each(cc.find('ActiveNode', this.node).children, function (element) {
            element.getComponent(cc.Animation).stop();
            element.opacity = 0;
        });
        _.each(cc.find('ScoreNode', this.node).children, function (element) {
            element.getComponent(cc.Animation).stop();
            element.color = cc.Color.WHITE;
        });
    },      // 刷新子域的纹理
    _updateSubDomainCanvas() {
        if (window.sharedCanvas !== undefined) {
            this.tex.initWithElement(window.sharedCanvas);
            this.tex.handleLoadedTexture();
            this.rankingNode.spriteFrame = new cc.SpriteFrame(this.tex);
        }
    },      // called every frame
    update: function (dt) {
        if (this.subContentNode.active) {        //子域显示才刷新
            this._updateSubDomainCanvas();
        }
        if (this.gameStatus === 1) {
            var self = this;
            this.timeDown = this.timeDown + dt;
            if (this.timeDown >= this.timeDownThreshold) {
                this.gameStatus = 2;
                this.timeDown = 0;
                _.each(cc.find('ActiveNode', this.node).children, function (element) {
                    element.getComponent(cc.Animation).stop();
                    element.opacity = 0;
                });
                _.each(cc.find('ScoreNode', this.node).children, function (element) {
                    element.getComponent(cc.Animation).stop();
                    element.color = cc.Color.WHITE;
                });
                _.each(this.targetIndex, function (index) {
                    cc.find('ActiveNode', self.node).children[index].opacity = 255;
                    cc.find('ScoreNode', self.node).children[index].color = cc.Color.RED;
                });
                this.hoodleSprite.spriteFrame = new cc.SpriteFrame(cc.url.raw('resources/images/ball/' + _.random(0, 6) + '.png'));
                this.hoodleSprite.node.active = true;
                this.hoodleSprite.node.position = this.hoodleVec2;
                var hoodleRigidBody = this.hoodleSprite.node.getComponent(cc.RigidBody);
                hoodleRigidBody.linearVelocity = cc.v2(0, 0);
                cc.audioEngine.stop(this.roundAudioID); //停止音效
                cc.audioEngine.play(cc.url.raw("resources/sound/turn.mp3"), false, 0.5);
            }
        }
    },
    getAngle: function (vec1, vec2) {
        var x = Math.abs(vec1.x - vec2.x);  // 直角的边长
        var y = Math.abs(vec1.y - vec2.y);
        var z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));// 斜边长
        if (z === 0) return 0;
        var radina = Math.acos(y / z); // 弧度
        return 180 / (Math.PI / radina); //角度
    }
});
